import { ref, computed, Transition, reactive, onMounted } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import {
  SecuritiesPropertyConfigCreatePropertyConfig,
  SecuritiesPropertyConfigGetPropertyConfig
} from "@/api/stu/Cecurity"
import { useWatermark } from "@pureadmin/utils";
export function useAssetAllocation() {
  const pattern = /^[1-9]\d*$/;
  const route = useRoute()
  const dataList = ref();
  const CreditFrom = ref();
  const pureref = ref()
  const loading = ref<boolean>(false);
  const DialogVisible = ref<boolean>(false);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 15, 30],
    background: true
  });

  const RefForm = reactive({
    Name: "",
    class: "",
    volatility: "",
    yield: "",
    Management: "",
    FixedIncome: "",
    IncomeEquity: "",
    otherness: ""
  });
  // 等级
  const Ncalss = [
    { label: "保守型", value: "bsx" },
    { label: "稳健型", value: "wjx" },
    { label: "平衡型", value: "phx" },
    { label: "成长型", value: "czx" },
    { label: "进取型", value: "qjx" },
  ]
  const rules = {
    Name: [
      { required: true, message: '请输入名称', trigger: 'blur' },
      { min: 4, max: 15, message: '请输入4-15个字符的名称', trigger: ['blur', 'change'], }
    ],
    class: [
      {
        required: true,
        message: '请选择安全等级',
        trigger: 'change',
      }
    ],
    volatility: [
      // { required: true, message: '点击输入预期波动率' },
      // { type: 'number', message: '只能输入数值' },
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (value < 0.1) {
            return callback(new Error('最小数值不能小于0'))
          }
          if (value > 32) {
            return callback(new Error('最大值不能超过32'))
          }
          // if (RefForm.class.value == 'bsx' && value > 0.5) {
          //   return callback(new Error('该类型接受范围不能超过0.5%'))
          // } else if (RefForm.class.value == 'wjx' && value > 5) {
          //   return callback(new Error('该类型接受范围不能超过5%'))
          // } else if (RefForm.class.value == 'phx' && value > 10) {
          //   return callback(new Error('该类型接受范围不能超过10%'))
          // } else if (RefForm.class.value == 'czx' && value > 17.5) {
          //   return callback(new Error('该类型接受范围不能超过17.5%'))
          // } else if (RefForm.class.value == 'qjx' && value > 32) {
          //   return callback(new Error('该类型接受范围不能超过32%'))
          // }
          else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    yield: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (value > 100 || typeof value == "string" || !pattern.test(value)) {
            return callback(new Error('请输入100以内的预期收益率，只能输入整数'))
          } else {
            return callback()
          }
        }
      }
      // { required: true, message: '点击输入预期收益率' },
      // { type: 'number', message: '只能输入数值' },
    ],
    Management: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          console.log("s001", pattern.test(value))
          if (value > 100 || typeof value == "string" || !pattern.test(value)) {
            return callback(new Error('请输入100以内的现金管理类，只能输入整数'))
          } else {
            return callback()
          }
        }
      }
    ],
    FixedIncome: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (value > 100 || typeof value == "string" || !pattern.test(value)) {
            return callback(new Error('请输入100以内的固定收益类，只能输入整数'))
          } else {
            return callback()
          }
        }
      }
    ],
    IncomeEquity: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (value > 100 || typeof value == "string" || !pattern.test(value)) {
            return callback(new Error('请输入100以内的权益收益类，只能输入整数'))
          } else {
            return callback()
          }
        }
      }
    ],
    otherness: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (value > 100 || typeof value == "string" || !pattern.test(value)) {
            return callback(new Error('请输入100以内的另类及其他，只能输入整数'))
          } else {
            return callback()
          }
        }
      }
    ]
  }

  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "资产配置方案",
      prop: "projectName"
    }, {
      label: "预期波动率(%)",
      prop: "expectedVolatility",
    }, {
      label: "预期收益率(%)",
      prop: "expectedYield"
    }, {
      label: "现金管理类(%)",
      prop: "cashManagement"
    }, {
      label: "固定收益类(%)",
      prop: "fixedIncome"
    }, {
      label: "权益收益类(%)",
      prop: "incomeFromEquity"
    }, {
      label: "另类及其他(%)",
      prop: "rests"
    }
  ];
  const BtnLoading = ref<boolean>(false)
  function CreateAsset() {
    console.log("新建")
    DialogVisible.value = true
  }

  function handleSizeChange(val) {
    getList()
  }

  function handleCurrentChange(val) {
    getList()
    // console.log("---", val)
  }

  function SubmitVisible(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      const AddNum = (Number(RefForm.Management) + Number(RefForm.FixedIncome) + Number(RefForm.IncomeEquity) + Number(RefForm.otherness));
      if (AddNum > 100) {
        ElMessage.warning("现金管理类,固定收益类,权益收益类,另类及其他总和超过100%")
        return
      }
      if (AddNum !== 100) {
        ElMessage.warning("现金管理类,固定收益类,权益收益类,另类及其他总和未达到100%")
        return
      }

      const data = {
        "planId": route.query.planId,
        "taskId": route.query.taskId,
        projectName: RefForm.Name,
        riskGrade: RefForm.class.label,
        expectedVolatility: RefForm.volatility,
        expectedYield: RefForm.yield,
        cashManagement: RefForm.Management,
        fixedIncome: RefForm.FixedIncome,
        incomeFromEquity: RefForm.IncomeEquity,
        rests: RefForm.otherness
      };
      BtnLoading.value = true;
      const res = await SecuritiesPropertyConfigCreatePropertyConfig(data);
      if (res.success) {
        ElMessage.success(res.msg);
        BtnLoading.value = false;
        getList()
        CloseVisible(row);
      } else {
        ElMessage.error(res.msg);
        setTimeout(() => { BtnLoading.value = false; }, 1500)
      }
    })
  }

  function CloseVisible(row: FormInstance | undefined) {
    DialogVisible.value = false
    row.resetFields();
  }

  async function getList() {
    const data = {
      "planId": route.query.planId,
      "taskId": route.query.taskId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
    };
    const res = await SecuritiesPropertyConfigGetPropertyConfig(data);
    if (res.success) {
      dataList.value = res.data.items;
      pagination.total = res.data.totalCount
    } else {
      ElMessage.error(res.msg);
    }
  }

  onMounted(() => {
    getList()
  })

  return {
    rules,
    Ncalss,
    RefForm,
    columns,
    loading,
    pureref,
    dataList,
    BtnLoading,
    pagination,
    CreditFrom,
    DialogVisible,
    CreateAsset,
    handleSizeChange,
    handleCurrentChange,
    SubmitVisible,
    CloseVisible
  }
}
